package com.cjm.nio.ifeve;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * <a href="http://ifeve.com/channels/">Java NIO系列教程（二） Channel</a>
 */
public class ChannelDemo {
    public static void main(String[] args) throws IOException {
        b();
    }

    private static void b() {
        long start = System.currentTimeMillis();
        try (FileChannel scr = FileChannel.open(Paths.get("D:\\a\\b.mp4"), StandardOpenOption.READ);
        FileChannel des = FileChannel.open(Paths.get("D:\\c.mp4"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE)){

            scr.transferTo(0, scr.size(), des);
        }catch (Exception e) {
            System.err.println(e.getMessage());
        }
        long end = System.currentTimeMillis();
        System.err.println("total spend times = " + (end - start));
    }

    private static void a() throws IOException {
        long start = System.currentTimeMillis();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel src = null;
        FileChannel des = null;

        try {
            fis = new FileInputStream("D:\\a\\b.mp4");
            fos = new FileOutputStream("D:\\a.mp4");
            src = fis.getChannel();
            des = fos.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while (src.read(buffer) != -1) {
                buffer.flip();
                des.write(buffer);
                buffer.clear();
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            src.close();
            des.close();
            fis.close();
            fos.close();
        }
        long end = System.currentTimeMillis();
        System.err.println("total spend time = " + (end - start));
    }

}
